<template>
  <div class="setting">
    <div class="user-info" v-loading="userInfoLoading">
      <mini-title-view title="修改信息"></mini-title-view>
      <el-form
        :model="userInfo"
        label-width="100px"
        ref="userInfo"
        :rules="rules"
      >
        <el-form-item label="登录账号" style="width: 90%">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名" style="width: 90%" prop="name">
          <el-input
            v-model="userInfo.name"
            :clearable="true"
            autocomplete="off"
            @input="checkData"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" style="width: 24%">
          <el-select
            v-model="userInfo.gender"
            placeholder="请选择性别"
            @input="checkData"
          >
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
            <el-option label="保密" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" style="width: 90%" prop="phone">
          <el-input
            v-model="userInfo.phone"
            :clearable="true"
            autocomplete="off"
            @input="checkData"
          ></el-input>
        </el-form-item>
        <el-form-item label="简介" style="width: 90%" prop="introduce">
          <el-input
            v-model="userInfo.introduce"
            type="textarea"
            :rows="3"
            maxlength="100"
            show-word-limit
            :clearable="true"
            autocomplete="off"
            @input="checkData"
          ></el-input>
        </el-form-item>
        <el-form-item style="width: 86%">
          <el-tooltip
            :content="isChange ? '可修改' : '数据无变化，不可修改'"
            placement="top"
            effect="light"
          >
            <el-button
              type="success"
              :disabled="!isChange"
              @click="update"
              :loading="updateLoading"
              >完成</el-button
            >
          </el-tooltip>
        </el-form-item>
      </el-form>
    </div>
    <div class="user-pwd">
      <MiniTitleView title="修改密码" />
      <el-form
        :model="pwdForm"
        label-width="100px"
        ref="pwdForm"
        :rules="pwdRules"
        style="margin-left: 20px"
      >
        <el-form-item label="旧密码" class="form-item" prop="oldPwd">
          <el-input
            v-model="pwdForm.oldPwd"
            type="password"
            :clearable="true"
            autocomplete="off"
            @blur="change"
            @input="inputOldPwd"
          ></el-input>
          <div
            class="tip"
            v-loading="verifyLoading"
            element-loading-spinner="el-icon-loading"
          >
            <span v-show="!flag && isShow" style="color: #f56c6c">
              <i class="el-icon-circle-close"></i>密码错误
            </span>
            <span v-show="flag && isShow" style="color: #67c23a">
              <i class="el-icon-circle-check"></i>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="新密码" class="form-item" prop="newPwd">
          <el-input
            v-model="pwdForm.newPwd"
            type="password"
            :clearable="true"
            autocomplete="off"
            :disabled="!flag"
          ></el-input>
          <div
            class="tip"
            style="color: #67c23a"
            v-show="pwdForm.newPwd !== ''"
          >
            <i class="el-icon-circle-check"></i>
          </div>
        </el-form-item>
        <el-form-item label="确认新密码" class="form-item" prop="verifyNewPwd">
          <el-input
            v-model="pwdForm.verifyNewPwd"
            type="password"
            :clearable="true"
            autocomplete="off"
            :disabled="!flag"
          ></el-input>
          <div
            class="tip"
            style="color: #67c23a"
            v-show="
              pwdForm.newPwd === pwdForm.verifyNewPwd &&
              pwdForm.verifyNewPwd !== ''
            "
          >
            <i class="el-icon-circle-check"></i>
          </div>
        </el-form-item>
        <el-form-item style="width: 20%">
          <el-button type="primary" @click="updatePwd" :loading="updateLoading"
            >修改</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  getUserInfo,
  updateUserInfo,
  verifyOldPassword,
} from "@/api/user/user";
import MiniTitleView from "@/components/MiniTitleView.vue";
import userModule from "@/utils/userInfo";

export default {
  name: "Setting",
  components: {
    MiniTitleView,
  },
  data() {
    return {
      userInfo: {
        name: "",
        gender: 0,
        phone: "",
        introduce: "",
      },
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        introduce: [{ required: true, message: "请输入简介", trigger: "blur" }],
      },
      copyInfo: {},
      isChange: false,
      userInfoLoading: false,
      updateLoading: false,

      pwdForm: {
        oldPwd: "",
        newPwd: "",
        verifyNewPwd: "",
      },
      pwdRules: {
        oldPwd: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
        newPwd: [{ required: true, message: "请输入新密码", trigger: "blur" }],
        verifyNewPwd: [
          { required: true, message: "请确认新密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value !== this.pwdForm.newPwd) {
                callback(new Error("两次输入的密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      verifyLoading: false,
      updatePwdLoading: false,
      isShow: false,
      flag: false,
    };
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        this.userInfoLoading = true;
        const res = await getUserInfo({ id: userModule.getUser().id });
        Object.assign(this.userInfo, res.data);
        Object.assign(this.copyInfo, res.data);

        this.userInfo.gender = this.userInfo.gender.toString();
        this.copyInfo.gender = this.copyInfo.gender.toString();
        this.userInfo.introduce = this.userInfo.introduce || "";
        this.copyInfo.introduce = this.copyInfo.introduce || "";
      } catch {
        this.$message.error("获取用户信息失败");
      } finally {
        this.userInfoLoading = false;
      }
    },
    // 检查数据是否变化
    checkData() {
      for (let key in this.userInfo) {
        if (this.userInfo[key] !== this.copyInfo[key]) {
          this.isChange = true;
          return;
        }
      }
      this.isChange = false;
    },
    // 修改信息
    update() {
      this.$refs.userInfo.validate(async (v) => {
        if (v) {
          try {
            this.updateLoading = true;
            const res = await updateUserInfo(this.userInfo);
            this.getUserInfo();
            this.$router.go(0);
          } catch {
            this.$message.error("修改失败");
          } finally {
            this.updateLoading = false;
          }
        }
      });
    },
    // 监听密码框变化
    inputOldPwd() {
      if (this.pwdForm.oldPwd === "") {
        this.isShow = false;
        this.flag = false;
        this.$refs.pwdForm.resetFields();
      }
    },
    // 判断旧密码
    async change() {
      try {
        this.verifyLoading = true;
        if (this.pwdForm.oldPwd === "") return;
        const res = await verifyOldPassword({
          userId: userModule.getUser().id,
          password: this.pwdForm.oldPwd,
        });
        this.flag = res.data;
        this.isShow = true;
      } finally {
        this.verifyLoading = false;
      }
    },
    // 修改密码
    updatePwd() {
      this.$refs.pwdForm.validate(async (v) => {
        if (v) {
          try {
            this.updateLoading = true;
            const res = await updateUserInfo({
              id: userModule.getUser().id,
              password: this.pwdForm.newPwd,
            });
            this.$message.warning("请重新登录");
            localStorage.removeItem("u_u");
            localStorage.removeItem("u_t");
            this.$router.push("/login");
          } catch {
            this.$message.error("修改失败");
          } finally {
            this.updateLoading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.setting {
  height: 100%;
  .user-info {
    padding-top: 2px;
    padding-bottom: 10px;
    box-shadow: 0 0 6px #ccc;
  }
  .user-pwd {
    margin-top: 20px;
    padding-top: 2px;
    padding-bottom: 10px;
    box-shadow: 0 0 6px #ccc;
    .form-item {
      position: relative;
      width: 50%;
      .tip {
        position: absolute;
        top: 0;
        right: -92px;
        width: 82px;
        font-size: 15px;
        text-align: left;
        i {
          margin-right: 4px;
        }
      }
    }
  }
}
</style>